<?php

namespace Api\Controller;

use Common\Controller;
use Common\Utils\validate\Validate;

class CouponController extends Controller\ApiController {

    function receive() {
        //需要登录
        $user_info = $this->auth();
        $coupon_id = I('id');
        if (!is_numeric($coupon_id))
            $this->error('参数错误');
        $model = D('Coupon');
        $result = $model->receiveCoupon($coupon_id, $user_info['user_id']);
        if (!$result)
            $this->error($model->last_msg());
        $this->success();
    }

    public function receiveFromUser() {
        //1.验证是否登陆
        parent::auth();
        //2.接收参数并验证
        $couponCode = getParameter('coupon_code');


        if (emptys($couponCode))
            $this->error('优惠卷不存在');


        //3.用户领取优惠券
        $userInfo = $this->getUserInfo();
        $couponCode = couponEDC($couponCode,false);
        $result = D('Coupon')->receiveFromUser($userInfo['user_id'], $couponCode);
        if (!$result)
            $this->error(D('Coupon')->last_msg());
        $this->success('领取成功！');
    }

    public function isReceive() {
        //需要登录
        $user_info = $this->auth();
        $coupon_id = I('id');
        $model = D('Coupon'); //checkCoupon
        $msg_id = I('id');
        $msg_id = explode(',', trim($msg_id, ','));
        $data = array();
        foreach ($msg_id as $id) {
            if ($id == 0 || !is_numeric($id))
                continue;
            $data[] = array(
                'id' => $id,
                'is_receive' => (int) $model->checkCoupon($id, $user_info['user_id'])
            );
        }
        $this->output($data);
    }

}
